package com.lbloca.locate.utils;


import android.app.Activity;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限请求util
 */
public class PermissionUtils {
    private static List<Callback> callbackList = new ArrayList<>();
    private static int requestCode;
    private static int[] results;
    private static Object waitLock = new Object();

    public interface Callback {

        void onGranted(String permission);

        void onDenied(String permission);
    }

    public static void requestPermission(Activity activity, String[] permissions, Callback callback) {
        callbackList.add(requestCode, callback);
        List<String> requestList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(activity, permissions[i]) ==
                    PackageManager.PERMISSION_GRANTED) {
                callback.onGranted(permissions[i]);
            } else {
                requestList.add(permissions[i]);
            }
        }
        if (requestList.size() > 0) {
            ActivityCompat.requestPermissions(activity, permissions, requestCode++);
        }
    }

    public static void onRequestPermissionsResult(
            int requestCode, String[] permissions, int[] grantResults) {
        System.out.println("requestCode=" + requestCode + " permissions-leng=" + permissions.length);
        Callback callback = callbackList.get(requestCode);
        if (callback == null) {
            for (int i = 0, n = 0; i < results.length; i++) {
                if (results[i] == -2) {
                    results[i] = grantResults[n++];
                }
            }
            synchronized (waitLock) {
                try {
                    waitLock.notifyAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    callback.onGranted(permissions[i]);
                } else {
                    callback.onDenied(permissions[i]);
                }
            }
        }
    }
}
